package com.itheima.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/*
* 处理统一字符集的过滤器
* */
@WebFilter(value = "/*",initParams = {@WebInitParam(name="encoding",value = "UTF-8")})
public class EncondingFilter implements Filter {
    private String encoding =null;
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        encoding = filterConfig.getInitParameter("encoding");
    }
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //类型转换
        HttpServletRequest request= (HttpServletRequest) servletRequest;
        HttpServletResponse response= (HttpServletResponse) servletResponse;

        request.setCharacterEncoding(encoding);
        response.setContentType("text/html;charset="+encoding);

        filterChain.doFilter(request,response);
    }

    @Override
    public void destroy() {

    }

}
